package com.jielihaofeng.source;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.logging.LoggingHandler;
import lombok.extern.slf4j.Slf4j;

/**
 * @author Johnnie Wind
 * @description 测试连接超时参数
 * @date 2021/11/19 10:21
 */
@Slf4j
public class TestConnectionTimeout {
    public static void main(String[] args) {
        NioEventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(group);
            bootstrap.channel(NioSocketChannel.class);
            // 连接超时参数，多少毫秒超时，抛出 ConnectTimeoutException 异常
            // 设置5秒，但是2秒就出现了Java的网络异常：
            // io.netty.channel.AbstractChannel$AnnotatedConnectException: Connection refused: no further information: localhost/127.0.0.1:8080
            // SO_TIMEOUT 主要用于用于阻塞IO，因为阻塞IO中的accept和read默认是无限阻塞的，这个参数可以配置这个时候的超时时间
            bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 5000);
            bootstrap.handler(new LoggingHandler());
            ChannelFuture channelFuture = bootstrap.connect("localhost", 8080);
            Channel channel = channelFuture.sync().channel();
            channel.closeFuture().sync();
        } catch (Exception e) {
            // io.netty.channel.ConnectTimeoutException: connection timed out: localhost/127.0.0.1:8080
            e.printStackTrace();
            log.debug("timeout");
        } finally {
            group.shutdownGracefully();
        }
    }
}
